package com.chart.web.controller.doubao;

import com.chart.common.core.domain.AjaxResult;
import com.chart.web.controller.chart.dto.DoubaoAiDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/doubao/ai")
public class DoubaoAiController {


    @Value("${doubao.api.url}") // API 地址
    private String doubaoApiUrl;

    @Value("${doubao.api.key}") // API Key
    private String doubaoApiKey;

    @Value("${doubao.api.model}") // model
    private String model;


    private final RestTemplate restTemplate = new RestTemplate();


    @PostMapping("/doubaoAi")
    public AjaxResult  doubaoAi(@RequestBody DoubaoAiDTO doubaoAiDTO)  {

        String detail = doubaoAiDTO.getDetail();
        String imageUrl = doubaoAiDTO.getImageUrl();


        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + doubaoApiKey);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", model);

        List<Map<String, Object>> messages = new ArrayList<>();
        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");

        // 构建内容
        List<Map<String, String>> content = new ArrayList<>();
        Map<String, String> textContent = new HashMap<>();
        textContent.put("type", "text");
        textContent.put("text",detail );


        Map<String, String> imageContent = new HashMap<>();
        imageContent.put("type", "image_url");
        imageContent.put("image_url", imageUrl); // 使用传入的图片 URL

        content.add(textContent);
        content.add(imageContent);

        message.put("content", content);
        messages.add(message);

        requestBody.put("messages", messages);
        requestBody.put("detail", detail);

        // 发送 POST 请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                doubaoApiUrl,
                HttpMethod.POST,
                requestEntity,
                String.class
        );

        String body = response.getBody();

        return AjaxResult.success(body);
    }






}
